package com.kofan.shelter.commons.util.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kofan.shelter.api.bean.JsonResult;
import com.kofan.shelter.api.bean.KofanEntity;
import com.kofan.shelter.commons.util.exception.CommonException;
import com.kofan.shelter.commons.util.utils.SecurityUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

public class KofanServiceImpl<M extends KofanBaseMapper<T>, T extends KofanEntity> extends ServiceImpl<M, T> implements IKofanService<T, M> {

    /**
     * 获取数据列表
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getByPage(BaseQuery query) {
        return null;
    }

    @Override
    public JsonResult get(BaseQuery query) {
        return null;
    }

    /**
     * 根据实体ID获取实体信息
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public JsonResult info(String id) {
        if (id == null) {
            return JsonResult.error("记录ID不能为空");
        }
        Object result = this.getInfo(id);
        if (result == null) {
            return JsonResult.error("记录不能为空");
        }
        return JsonResult.success(result);
    }

    /**
     * 根据ID获取记录信息
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        T entity = this.getById(id);
        return entity;
    }

    /**
     * 传入实体对象添加记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult add(T entity) {
        entity.setIsDel("0");
        if(StringUtils.isEmpty(entity.getCreateUserId())){
            entity.setCreateUserId(SecurityUtils.getUserId());
        }
        entity.setCreateTime(DateUtil.now());
        boolean result = this.save(entity);
        if (!result) {
            throw new CommonException("新增失败");
        }
        return JsonResult.success();
    }


    /**
     * 传入实体对象添加记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult addCrontab(T entity) {
        entity.setIsDel("0");
        entity.setCreateTime(DateUtil.now());
        boolean result = this.save(entity);
        if (!result) {
            throw new CommonException("新增失败");
        }
        return JsonResult.success();
    }

    /**
     * 传入实体对象更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult update(T entity) {
        entity.setLastUpdateUserId(SecurityUtils.getUserId());
        entity.setLastUpdateTime(DateUtil.now());
        boolean result = this.updateById(entity);
        if (!result) {
            throw new CommonException("修改失败");
        }
        return JsonResult.success();
    }


    @Override
    public JsonResult updateCrontab(T entity) {
        entity.setLastUpdateTime(DateUtil.now());
        boolean result = this.updateById(entity);
        if (!result) {
            throw new CommonException("修改失败");
        }
        return JsonResult.success();
    }

    /**
     * 根据ID删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(T entity) {
        String tableId = null;// 主键 小写的
        String id = null; // 主键值

        // 获取主键
        Field[] fields = ReflectUtil.getFields(entity.getClass());
        for (int u = 0; u < fields.length; u++) {
            TableId annotationTableId = fields[u].getAnnotation(TableId.class);
            if (annotationTableId != null) {
                tableId = annotationTableId.value();
                fields[u].setAccessible(true);
                try {
                    id = fields[u].get(entity).toString();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        if (StrUtil.isEmpty(tableId)) {
            throw new CommonException(entity.getClass().getSimpleName() + "@TableId注解不存在");
        }

        // 设置Mark=0
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_del", "1");
        updateWrapper.set("last_update_user_id", SecurityUtils.getUserId());
        updateWrapper.set("last_update_time", DateUtil.now());
        updateWrapper.eq(tableId, id);
        boolean result = update(updateWrapper);
        if (!result) {
            throw new CommonException("删除失败");
        }
        return JsonResult.success("删除成功");
    }

    @Override
    public JsonResult deleteCrontab(T entity) {
        String tableId = null;// 主键 小写的
        String id = null; // 主键值

        // 获取主键
        Field[] fields = ReflectUtil.getFields(entity.getClass());
        for (int u = 0; u < fields.length; u++) {
            TableId annotationTableId = fields[u].getAnnotation(TableId.class);
            if (annotationTableId != null) {
                tableId = annotationTableId.value();
                fields[u].setAccessible(true);
                try {
                    id = fields[u].get(entity).toString();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        if (StrUtil.isEmpty(tableId)) {
            throw new CommonException(entity.getClass().getSimpleName() + "@TableId注解不存在");
        }

        // 设置Mark=0
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_del", "1");
        updateWrapper.set("last_update_time", DateUtil.now());
        updateWrapper.eq(tableId, id);
        boolean result = update(updateWrapper);
        if (!result) {
            throw new CommonException("删除失败");
        }
        return JsonResult.success("删除成功");
    }

    /**
     * 根据ID删除记录
     *
     * @param ids 记录ID
     * @return
     */
    @Override
    public JsonResult deleteByIds(String[] ids, String tableName) {
        if (ids.length == 0) {
            return JsonResult.error("记录ID不能为空");
        }
        // 设置Mark=0
        Integer totalNum = 0;
        for (String id : ids) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("is_del", "1");
            updateWrapper.set("last_update_user_id", SecurityUtils.getUserId());
            updateWrapper.set("last_update_time", DateUtil.now());
            updateWrapper.eq(tableName + "_id", id);
            boolean result = update(updateWrapper);
            if (result) {
                totalNum++;
            }
        }
        if (totalNum != ids.length) {
            throw new CommonException("删除失败");
        }
        return JsonResult.success("删除成功");
    }

    @Override
    public boolean saveBatch(Collection<T> entityList, int batchSize) {
        List<T> list=(List<T>)entityList;
        Integer integer = baseMapper.insertBatchSomeColumn(list);
        if (integer.equals(batchSize)){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public M getKofanBaseMapper() {
        return super.baseMapper;
    }
}
